<template>
  <div class="article-detail-container">
    <!-- 主内容区 -->
    <el-container class="main-container" v-if="currDetailData">
      <div class="main-content">
        <!-- 页面主标题 -->
        <div class="main-title">{{ currDetailData.title }}</div>

        <!-- 发布时间和作者 -->
        <div class="publish-info">
          <span class="publish-time">发布时间： {{ timestampToDayHM(currDetailData.updatedAt) }}</span>
        </div>

        <h3 v-if="currDetailData.picList">图片内容</h3>
        <!-- 图片缩略图列表 -->
        <div class="image-thumbnails">
          <el-image
            style="width:100px; height:100px;"
            v-for="(image, index) in currDetailData.picList" 
            :key="index"
            :src='image'
            :zoom-rate="1.2"
            :max-scale="7"
            :min-scale="0.2"
            :preview-src-list="currDetailData.picList"
            show-progress
            :initial-index="4"
            fit="cover"
          />
        </div>

        <!-- 多媒体元素示例 -->
        <div class="media-section" v-if="currDetailData.videoUrl">
          <h3>视频内容</h3>
        </div>
        <div class="video-view" v-if="currDetailData.videoUrl">
          <video controls width="100%">
            <source :src="currDetailData.videoUrl" type="video/mp4">
            您的浏览器不支持 video 标签。
          </video>
        </div>

        <!-- 正文内容 -->
        <div class="article-content">
          <h3>正文内容</h3>
          <div>
            {{ currDetailData.description }}
          </div>
        </div>
      </div>
    </el-container>

    <div class="footer" v-if="currDetailData">
      <!-- 点赞与收藏按钮 -->
      <div class="action-buttons">
        <el-button v-if="currDetailData.isLiked" type="primary" icon="ArrowUpBold" @click="toggleLike">
          {{ currDetailData.likes }}点赞
        </el-button>
        <el-button v-else type="primary" plain icon="ArrowUpBold" @click="toggleLike">
          {{ currDetailData.likes }}点赞
        </el-button>
        <el-button v-if="currDetailData.isFavorited" type="danger" icon="StarFilled" @click="toggleFavorite">
          已收藏
        </el-button>
        <el-button v-else type="danger" plain icon="Star" @click="toggleFavorite">
          {{ currDetailData.favs }}人收藏
        </el-button>
      </div>
    </div>



    <!-- 评论列表 -->
    <!-- <el-card class="comments-card">
      <h2 class="comments-title">评论</h2>
      <div class="comment-list">
        <div v-for="comment in commentList" :key="comment.id" class="comment-item">
          <div class="comment-author">
            <el-avatar shape="square" size="medium" :src="comment.user.pic" style="float: left; margin-right: 10px;"></el-avatar>
            {{ comment.user.nickName }}
            <div class="comment-date">{{ timestampToDayHM(comment.updatedAt) }}</div>
          </div>
          <div class="comment-content">{{ comment.content }}</div>
        </div>
      </div>
      <p class="no-data" v-if="commentList.length==0">暂无评论</p>
    </el-card> -->

    <!-- 发表评论 -->
    <!-- <el-card class="add-comment-card">
      <h2 class="add-comment-title">发表评论</h2>
      <el-form label-width="130px" :model="editForm" :rules="rules" ref="formRef">
        <el-input
          v-model="editForm.content"
          :rules="rules"
          type="textarea"
          :rows="4"
          placeholder="请输入你的评论"
        ></el-input>
        <el-button type="primary" class="submit-comment-btn" @click="submitForm">提交评论</el-button>
      </el-form>
    </el-card> -->
  </div>
</template>
  
<script setup lang="ts">
  import { ref, reactive, nextTick, toRef, computed, onMounted } from "vue";
  import baseService from "@/service/baseService";
  import { ElMessage, ElMessageBox } from "element-plus";
  import { timestampToDayHM, timestampToHM, timestampToDate, formatAmount } from "@/utils/utils"
  import { fileUploader } from '@/utils/upload.js'
  import { useRouter, useRoute } from 'vue-router';
  import { getCache, removeCache } from "@/utils/cache";
  import { CacheToken } from "@/constants/cacheKey";
  import { useStore } from 'vuex';
  const store = useStore();

  // 查询参数
  const queryForm = reactive({
    deptName: "",
    pageNo: 1,
    pageSize: 10
  });
  const router = useRouter();
  const route = useRoute();
  // 列表内容数量
  const total = ref(0);
  // 列表是否加载
  const loading = ref(true);
  // 列表返回值
  const list = ref<any[]>([]);

  // 表单实例
  const formRef = ref();
  // 是否打开弹出框
  const open = ref(false);
  const openDetail = ref(false);
  // 弹出框标题
  const title = ref("");
  const commentList = ref<any[]>([]);
  const currDetailData = ref();
  
  // 提交表单数据
  let editForm = toRef(
    reactive({
      newsId: '',
      content: ''
    })
  );

  const currUser = computed(() => store.state.frontUser);

  const onInit = () => {
    const userInfo = getCache(CacheToken);
    if(userInfo){
      console.log('登录用户：', userInfo)
      store.commit('setFrontLoginUser', userInfo);//使用Vuex保存登录用户
    }else{
      router.push("/user/login");
    }
    // console.log('从Vuex获取登录用户！store.state.frontUser:', store.state.frontUser)
  };

  // 表单验证
  const rules = ref({
    content: [{ required: true, message: "规则名称不能为空", trigger: "blur" }],
  });

  /**
   * 表单重置
   */
   function reset() {
    editForm.value = {
      newsId: '',
      content: ''
    };
    nextTick(() => {
      formRef.value?.resetFields();
    });
  }

  function goBack(){
    router.back()
  }

  const getInfo = () => {
      const pid = route.query.nid
      console.log('从路由获取参数：', route.query)
      baseService.get(`/api/course/detail/${pid}`).then((res) => {
          console.log('获取详情：',res)
          currDetailData.value = res.data.course;
          commentList.value = res.data.commentList;
          loading.value = false;
      }).catch(() => {
          loading.value = false;
      });
  }

  //点赞
  const toggleLike = () => {
    const pid = route.query.nid
    baseService.get(`/api/course/like/${pid}`).then((res) => {
      loading.value = false;
      if(currDetailData.value.isLiked==0){
        currDetailData.value.isLiked=1
        currDetailData.value.likes++
        ElMessage.success('点赞成功')
      }else{
        currDetailData.value.isLiked=0
        currDetailData.value.likes--
        ElMessage.warning('已取消点赞')
      }
    }).catch(() => {
        loading.value = false;
    });
  }

  //收藏 
  const toggleFavorite = () => {
    const pid = route.query.nid
    baseService.get(`/api/course/fav/${pid}`).then((res) => {
      loading.value = false;
      if(currDetailData.value.isFavorited==0){
        currDetailData.value.isFavorited=1
        currDetailData.value.favs++
        ElMessage.success('收藏成功')
      }else{
        currDetailData.value.isFavorited=0
        currDetailData.value.favs--
        ElMessage.warning('已取消收藏')
      }
    }).catch(() => {
        loading.value = false;
    });
  }

  //发表评论
  function submitForm() {
    formRef.value.validate((valid: boolean) => {
      if (!valid) return;
      editForm.value.newsId = currDetailData.value.id
      baseService.post(`/api/course/comment`, editForm.value).then((res) => {
        if (res.code === 200) {
          ElMessage.success(res.msg);
          open.value = false;
          editForm.value.content=''
          getInfo();
        } else {
          ElMessage.error(res.msg);
        }
      });
    });
  }

  getInfo();

  onMounted(() => {
    onInit();
  });
</script>
  
<style scoped>
  .article-detail-container {
    max-width: 800px;
    margin: 0 auto;
    padding: 20px;
  }
  
  .article-card {
    margin-bottom: 20px;
  }
  
  .article-title {
    font-size: 24px;
    margin-bottom: 10px;
    color: #555;
  }
  
  .article-meta {
    font-size: 14px;
    color: #666;
    margin-bottom: 20px;
  }
  
  .article-content {
    font-size: 16px;
    line-height: 1.6;
    margin-bottom: 20px;
    white-space:break-spaces;
  }
  
  .image-thumbnails {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
    margin-bottom: 5px;
  }
  
  .thumbnail {
    width: 150px;
    height: 150px;
    cursor: pointer;
    border-radius: 4px;
    transition: transform 0.2s;
  }

  
  .comments-card {
    margin-bottom: 20px;
  }
  
  .comments-title {
    font-size: 20px;
    margin-bottom: 15px;
    color:#555;
    font-weight: normal;
  }
  
  .comment-item {
    margin-bottom: 15px;
    padding-bottom: 15px;
    border-bottom: 1px solid #eee;
  }
  
  .comment-author {
    font-weight: bold;
    margin-bottom: 5px;
    height: 45px;
  }
  
  .comment-content {
    font-size: 14px;
    color: #333;
    margin-bottom: 5px;
  }
  
  .comment-date {
    font-size: 12px;
    color: #999;
    padding-top: 8px;
  }
  
  .add-comment-card {
    margin-bottom: 20px;
  }
  
  .add-comment-title {
    font-size: 20px;
    margin-bottom: 15px;
    color:#555;
    font-weight: normal;
  }
  
  .submit-comment-btn {
    margin-top: 10px;
  }

  .action-buttons {
    display: flex;
    gap: 10px;
    margin-bottom: 20px;
  }
  .no-data{
    margin: 10px 0;
    color:#888;
  }
  .video-view{
    margin-bottom: 10px;
  }
  .warning{
    text-align: center;
    color: #e2a388;
    margin: 10px 0 30px 0;
  }


  .cctv-news-style {
  font-family: 'Microsoft YaHei', sans-serif;
  background-color: #f5f5f5;
  color: #333;
}

.header-container {
  background-color: #000;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 20px;
}

.logo {
  font-size: 28px;
  font-weight: bold;
  color: #ffcc00;
}

.nav-menu {
  background-color: transparent;
  border-bottom: none;
}

.nav-menu .el-menu-item {
  color: #fff;
}

.nav-menu .el-menu-item.is-active {
  background-color: rgba(255, 255, 255, 0.1);
}

.main-title {
  font-size: 32px;
  font-weight: bold;
  color: #333;
  text-align: center;
  margin-bottom: 20px;
}

.publish-info {
  font-size: 14px;
  color: #666;
  text-align: center;
  margin-bottom: 5px;
}

.publish-time,
.author {
  margin-right: 20px;
}

.article-content {
  font-size: 16px;
  line-height: 1.8;
}

.article-content h2 {
  font-size: 24px;
  color: #333;
  border-bottom: 2px solid #ccc;
  padding-bottom: 5px;
  margin-bottom: 15px;
}

.article-content p {
  margin-bottom: 15px;
}

.media-section {
  margin-top: 10px;
}

.media-section h2 {
  font-size: 24px;
  color: #333;
  margin-bottom: 10px;
}

.el-image {
  border-radius: 5px;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 450px;
  background-color: #f5f5f5;
  color: #999;
}

.image-slot .dot {
  animation: dots 1.5s infinite;
}
.main-content, .footer{
  clear: both;
}
.footer{
  margin-bottom: 30px;
}
h3{
  margin-bottom: 8px;
}
</style>